﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Data;
using System.Data.Common;
using System.Globalization;
using System.Web.Script.Services;
using System.Web.Security;
using System.Web.Services;
using System.Collections.ObjectModel;
using System.Text;
using System.Configuration;

using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data;



namespace TractRecord.Authenticated
{
    public partial class Projects : TractRecordBasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static ArrayList GetUsersProjects()
        {
            ArrayList values = new ArrayList();

            try
            {

                string userid = Membership.GetUser().ProviderUserKey.ToString();

                //Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>("TractRecordDB");
                //DbCommand cmd = db.GetStoredProcCommand("ProjectSummaryForUser_Get");

                DbCommand cmd = Code.DataAccess.Data.GetStoredProcCommand("tr_ProjectSummaryForUser_Get");
                cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@UserId", userid));

                IDataReader r = Code.DataAccess.Data.ExecuteReader(cmd);

                while (r.Read())
                {
                    values.Add(
                        new
                        {
                            ProjectId = r["ProjectId"].ToString(),
                            ProjectLink = r["Name"].ToString(),
                            Name = r["Name"].ToString(),
                            Description = r["Description"].ToString(),
                            ActiveInd = r["ActiveInd"].ToString(),
                            EmailId = r["EmailId"].ToString(),
                            EntryDt = WebCommon.FormatDate(r["EntryDt"].ToString(), "G"),
                            EmailLink = r["EntryDt"].ToString(),
                            EmailAddress = r["EmailAddress"].ToString(),
                            EmailCount = r["EmailCount"].ToString(),
                            ProjectEmail = r["ProjectEmail"].ToString()
                        });
                }

                //EmailLink = "<a href=\"" + r["EmailId"].ToString() + "\">" + r["EntryDt"].ToString() + "</a>",
                //ProjectLink = "<a href=\"" + r["ProjectId"].ToString() + "\">" + r["Name"].ToString() + "</a>",
                //((DateTime)r["EntryDt"]).ToString("G")
            }
            catch (Exception ex)
            {
                Code.Common.Log(ex.ToString(), ex.GetType().ToString(), 100, 0, System.Diagnostics.TraceEventType.Critical, "");
            }
            return values;
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string CreateProject(string ProjectName, string ProjectDescription)
        {
            string userid = Membership.GetUser().ProviderUserKey.ToString();

            try
            {
                //Random r = new Random((int)DateTime.Now.Ticks % Int32.MaxValue);
                StringBuilder s = new StringBuilder();
                //s.Append(DateTime.Now.Ticks.ToString());
                //int RandomNumber = r.Next(2, s.Length - 2);
                //s = s.Insert(RandomNumber, "-");

                s.Append("tr-");
                s.Append(Code.Base36.Encode(DateTime.Now.Ticks));

                s.Append(ConfigurationManager.AppSettings["DefaultEmailDomain"]);

                DbCommand cmd = Code.DataAccess.Data.GetStoredProcCommand("tr_Project_Ins");
                cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ProjectName", ProjectName));
                cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ProjectDescription", ProjectDescription));
                cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@UserId", userid));
                cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Email", s.ToString()));

                Code.DataAccess.Data.ExecuteNonQuery(cmd);

                ListDictionary replacements = new ListDictionary();
                replacements.Add("<%Name%>", Membership.GetUser().UserName);
                replacements.Add("<%ProjectName%>", ProjectName);
                replacements.Add("<%ProjectEmailAddress%>", s.ToString());

                WebCommon.GenerateEmailMessage(WebCommon.MailMessageType.NewProject, "New Project Created", Membership.GetUser().Email, replacements);
            }
            catch (Exception ex)
            {
                Code.Common.Log(ex.ToString(), ex.GetType().ToString(), 100, 0, System.Diagnostics.TraceEventType.Critical, "");

                return ex.ToString();
            }

            return string.Empty;
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static void UpdateProject(string ProjectId, string ProjectName, string ProjectDescription, string ActiveInd)
        {
            try
            {
                int booleanValue = Convert.ToInt32(Convert.ToBoolean(ActiveInd.ToLowerInvariant()));

                DbCommand cmd = Code.DataAccess.Data.GetStoredProcCommand("tr_Project_Upd");
                cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ProjectName", ProjectName));
                cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ProjectDescription", ProjectDescription));
                cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ActiveInd", booleanValue));
                cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ProjectId", ProjectId));

                Code.DataAccess.Data.ExecuteNonQuery(cmd);
            }
            catch (Exception ex)
            {
                Code.Common.Log(ex.ToString(), ex.GetType().ToString(), 100, 0, System.Diagnostics.TraceEventType.Critical, "");
                throw;
            }
        }


        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static void ActivateProject(string ProjectId, string ProjectName, string ProjectDescription, string ActiveInd)
        {
            UpdateProject(ProjectId, ProjectName, ProjectDescription, (!Convert.ToBoolean(ActiveInd.ToLowerInvariant())).ToString());
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static void DeleteProject(string ProjectId)
        {
            try
            {
                DbCommand cmd = Code.DataAccess.Data.GetStoredProcCommand("tr_Project_Del");
                cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ProjectId", ProjectId));

                Code.DataAccess.Data.ExecuteNonQuery(cmd);
            }
            catch (Exception ex)
            {
                Code.Common.Log(ex.ToString(), ex.GetType().ToString(), 100, 0, System.Diagnostics.TraceEventType.Critical, "");
                throw;
            }
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static ArrayList GetAlertEmails(string ProjectId)
        {
            ArrayList values = new ArrayList();

            try
            {
                DbCommand cmd = Code.DataAccess.Data.GetStoredProcCommand("tr_ProjectAlertEmails_Get");
                cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ProjectId", ProjectId));

                IDataReader r = Code.DataAccess.Data.ExecuteReader(cmd);

                while (r.Read())
                {
                    values.Add(
                        new
                        {
                            ProjectId = r["ProjectId"].ToString(),
                            ProjectAlertEmailId = r["ProjectAlertEmailId"].ToString(),
                            Email = r["Email"].ToString()
                        });
                }
            }
            catch (Exception ex)
            {
                Code.Common.Log(ex.ToString(), ex.GetType().ToString(), 100, 0, System.Diagnostics.TraceEventType.Critical, "");
                throw;
            }

            return values;
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static void AddAlertEmails(string ProjectId, string Email)
        {
            try
            {
                DbCommand cmd = Code.DataAccess.Data.GetStoredProcCommand("tr_ProjectAlertEmails_Ins");
                cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ProjectId", ProjectId));
                cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Email", Email));

                Code.DataAccess.Data.ExecuteNonQuery(cmd);
            }
            catch (Exception ex)
            {
                Code.Common.Log(ex.ToString(), ex.GetType().ToString(), 100, 0, System.Diagnostics.TraceEventType.Critical, "");
                throw;
            }
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static void DeleteAlertEmails(string ProjectAlertEmailId)
        {
            try
            {
                DbCommand cmd = Code.DataAccess.Data.GetStoredProcCommand("tr_ProjectAlertEmails_Del");
                cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ProjectAlertEmailId", ProjectAlertEmailId));

                Code.DataAccess.Data.ExecuteNonQuery(cmd);
            }
            catch (Exception ex)
            {
                Code.Common.Log(ex.ToString(), ex.GetType().ToString(), 100, 0, System.Diagnostics.TraceEventType.Critical, "");
                throw;
            }
        }
    }
}